package com.moyun.search.service;

import com.moyun.search.common.result.Result;
import com.moyun.search.common.result.ResultUtil;
import com.moyun.search.common.utils.FileUtils;
import com.moyun.search.dao.repository.ProjectFileLabRepository;
import com.moyun.search.domain.ProjectAttachment;
import com.moyun.search.domain.ProjectInfo;
import com.moyun.search.task.FileSyncElasticSearchTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.concurrent.ExecutorService;

/**
 * 文件上传服务
 * @author: zealon
 * @since: 2021/12/22
 */
@Service
@Slf4j
public class FileUploadService {

    @Autowired
    private ProjectAttachmentService projectAttachmentService;
    @Autowired
    private ExecutorService defaultQueueThreadPool;
    @Autowired
    private ProjectFileLabRepository projectFileLabRepository;
    @Autowired
    private ProjectInfoService projectInfoService;

    public Result upload(MultipartFile mulfile, Integer projectId){
        ProjectInfo project = projectInfoService.getById(projectId);
        if (project == null) {
            return ResultUtil.verificationFailed().buildMessage("上传失败，找不到此项目!projectId = " + projectId);
        }

        // 文件名
        String fileName = mulfile.getOriginalFilename();
        // 后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 大小
        String fileSize = FileUtils.getFileSize(mulfile.getSize());

        ProjectAttachment attachment = new ProjectAttachment();
        attachment.setProjectId(projectId);
        attachment.setFileName(fileName);
        attachment.setFilePath("");
        attachment.setFileSize(fileSize);
        attachment.setFileType(suffixName);
        attachment.setRemoveFlag(false);
        this.projectAttachmentService.create(attachment);

        // 异步同步文件到ES
        FileSyncElasticSearchTask task = new FileSyncElasticSearchTask(projectFileLabRepository, mulfile, attachment, project);
        this.defaultQueueThreadPool.execute(task);
        return ResultUtil.success();
    }
}